import { ipcMain } from 'electron'
import { dbConnection } from '../database/connection'

/**
 * 相册相关IPC处理
 */
export function setupAlbumIpc(): void {
  /**
   * 获取相册列表
   */
  ipcMain.handle('albums:getList', (_, { page = 1, limit = 50, orderBy = 'created_at', orderDirection = 'DESC' }) => {
    try {
      const db = dbConnection.getConnection()
      const offset = (page - 1) * limit
      
      // 获取总数
      const countQuery = 'SELECT COUNT(*) as total FROM albums'
      const countResult = db.prepare(countQuery).get() as { total: number }
      
      // 获取相册列表，包含照片数量
      const query = `
        SELECT 
          a.*,
          COUNT(pa.photo_id) as photo_count,
          p.file_path as cover_photo_path
        FROM albums a
        LEFT JOIN photo_albums pa ON a.id = pa.album_id
        LEFT JOIN photos p ON a.cover_photo_id = p.id
        GROUP BY a.id
        ORDER BY a.${orderBy} ${orderDirection}
        LIMIT ? OFFSET ?
      `
      const albums = db.prepare(query).all(limit, offset)
      
      return {
        success: true,
        data: {
          albums,
          total: countResult.total,
          page,
          limit,
          totalPages: Math.ceil(countResult.total / limit)
        }
      }
    } catch (error) {
      console.error('获取相册列表失败:', error)
      return {
        success: false,
        error: '获取相册列表失败'
      }
    }
  })

  /**
   * 获取相册详情
   */
  ipcMain.handle('albums:getById', (_, { id }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 获取相册信息
      const album = db.prepare('SELECT * FROM albums WHERE id = ?').get(id)
      
      if (!album) {
        return {
          success: false,
          error: '相册不存在'
        }
      }
      
      // 获取相册中的照片
      const photosQuery = `
        SELECT p.* FROM photos p
        JOIN photo_albums pa ON p.id = pa.photo_id
        WHERE pa.album_id = ?
        ORDER BY pa.added_at DESC
      `
      const photos = db.prepare(photosQuery).all(id)
      
      return {
        success: true,
        data: {
          ...album,
          photos
        }
      }
    } catch (error) {
      console.error('获取相册详情失败:', error)
      return {
        success: false,
        error: '获取相册详情失败'
      }
    }
  })

  /**
   * 创建相册
   */
  ipcMain.handle('albums:create', (_, { name, description }) => {
    try {
      const db = dbConnection.getConnection()
      
      const insertQuery = `
        INSERT INTO albums (name, description, created_at, updated_at)
        VALUES (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
      `
      const result = db.prepare(insertQuery).run(name, description)
      
      if (!result.lastInsertRowid) {
        return {
          success: false,
          error: '创建相册失败'
        }
      }
      
      // 获取新创建的相册
      const newAlbum = db.prepare('SELECT * FROM albums WHERE id = ?').get(result.lastInsertRowid)
      
      return {
        success: true,
        data: newAlbum
      }
    } catch (error) {
      console.error('创建相册失败:', error)
      return {
        success: false,
        error: '创建相册失败'
      }
    }
  })

  /**
   * 更新相册信息
   */
  ipcMain.handle('albums:update', (_, { id, updates }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 构建更新语句
      const fields = Object.keys(updates).map(key => `${key} = ?`).join(', ')
      const values = Object.values(updates)
      
      const updateQuery = `UPDATE albums SET ${fields}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`
      const result = db.prepare(updateQuery).run(...values, id)
      
      if (result.changes === 0) {
        return {
          success: false,
          error: '相册不存在或更新失败'
        }
      }
      
      return {
        success: true,
        data: { id, ...updates }
      }
    } catch (error) {
      console.error('更新相册失败:', error)
      return {
        success: false,
        error: '更新相册失败'
      }
    }
  })

  /**
   * 删除相册
   */
  ipcMain.handle('albums:delete', (_, { id }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 开始事务
      const transaction = db.transaction(() => {
        // 删除照片相册关联
        db.prepare('DELETE FROM photo_albums WHERE album_id = ?').run(id)
        
        // 删除相册
        const result = db.prepare('DELETE FROM albums WHERE id = ?').run(id)
        
        return result.changes > 0
      })
      
      const success = transaction(id)
      
      if (!success) {
        return {
          success: false,
          error: '相册不存在或删除失败'
        }
      }
      
      return {
        success: true,
        data: { id }
      }
    } catch (error) {
      console.error('删除相册失败:', error)
      return {
        success: false,
        error: '删除相册失败'
      }
    }
  })

  /**
   * 向相册添加照片
   */
  ipcMain.handle('albums:addPhoto', (_, { albumId, photoId }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 检查照片是否已在相册中
      const existing = db.prepare('SELECT * FROM photo_albums WHERE album_id = ? AND photo_id = ?').get(albumId, photoId)
      
      if (existing) {
        return {
          success: false,
          error: '照片已在相册中'
        }
      }
      
      // 添加照片到相册
      const insertQuery = `
        INSERT INTO photo_albums (album_id, photo_id, added_at)
        VALUES (?, ?, CURRENT_TIMESTAMP)
      `
      const result = db.prepare(insertQuery).run(albumId, photoId)
      
      if (!result.lastInsertRowid) {
        return {
          success: false,
          error: '添加照片到相册失败'
        }
      }
      
      return {
        success: true,
        data: { albumId, photoId }
      }
    } catch (error) {
      console.error('添加照片到相册失败:', error)
      return {
        success: false,
        error: '添加照片到相册失败'
      }
    }
  })

  /**
   * 从相册移除照片
   */
  ipcMain.handle('albums:removePhoto', (_, { albumId, photoId }) => {
    try {
      const db = dbConnection.getConnection()
      
      const deleteQuery = 'DELETE FROM photo_albums WHERE album_id = ? AND photo_id = ?'
      const result = db.prepare(deleteQuery).run(albumId, photoId)
      
      if (result.changes === 0) {
        return {
          success: false,
          error: '照片不在相册中或移除失败'
        }
      }
      
      return {
        success: true,
        data: { albumId, photoId }
      }
    } catch (error) {
      console.error('从相册移除照片失败:', error)
      return {
        success: false,
        error: '从相册移除照片失败'
      }
    }
  })
}